/**
 *Copyright (c) 2024 watereyes
 * workflow is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.workflow.baseConfig.service.impl;

import com.google.common.base.Objects;
import com.koron.workflow.baseConfig.bean.DepartmentStaffBean;
import com.koron.workflow.baseConfig.bean.RoleLineBean;
import com.koron.workflow.baseConfig.bean.RoleLineTeamBean;
import com.koron.workflow.baseConfig.bean.RoleLineTeamUserBean;
import com.koron.workflow.baseConfig.mapper.PostMapper;
import com.koron.workflow.baseConfig.mapper.RoleLineMapper;
import com.koron.workflow.baseConfig.mapper.StaffMapper;
import com.koron.workflow.baseConfig.service.RoleLineService;
import com.koron.workflow.common.bean.PageBean;
import com.koron.workflow.common.bean.StaffBean;
import com.koron.workflow.common.util.BusinessCode;
import com.koron.workflow.common.util.DisposeBeanUtil;
import com.koron.workflow.common.util.WorkflowUtil;
import org.apache.commons.collections.CollectionUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.koron.ebs.mybatis.TaskAnnotation;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.swan.bean.MessageBean;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author qingfeng
 * @description: TODO
 * @date 2020/4/13 14:11
 */
@Service
public class RoleLineServiceImpl implements RoleLineService {
	
	@Override
	@TaskAnnotation("queryForRoleCode")
	public List<StaffBean> queryForRoleId(SessionFactory factory, String roleId, String startUser){
		List<RoleLineTeamBean> roleLineTeams = review(factory, roleId);
		List<StaffBean> staffs = new ArrayList<StaffBean>();
		List<StaffBean> result = new ArrayList<StaffBean>();
		for(RoleLineTeamBean roleLineTeam : roleLineTeams) {
			List<RoleLineTeamUserBean> roleLineTeamUsers = roleLineTeam.getChildren();
			for(RoleLineTeamUserBean roleLineTeamUser : roleLineTeamUsers) {
				staffs.addAll(getStaffs(factory, roleLineTeamUser.getType(), roleLineTeamUser.getAccount()));
			}
			List<String> accounts = staffs.stream().filter(t -> t != null).map(t -> t.getAccount()).collect(Collectors.toList());
			if(accounts.contains(startUser)) {
				result.addAll(getStaffs(factory, roleLineTeam.getType(), roleLineTeam.getAccount()));
				staffs.clear();
			}
		}
		return result;
	}
	
	private List<StaffBean> getStaffs(SessionFactory factory, String type, String account){
		List<StaffBean> staffs = new ArrayList<StaffBean>();
		if(Objects.equal("0", type)) { //用户
			StaffBean staff = factory.getMapper(StaffMapper.class).queryForObject(account);
			staffs.add(staff);
		}
		if(Objects.equal("1", type)) { //岗位
			List<DepartmentStaffBean> departmentStaffs = factory.getMapper(PostMapper.class).queryPostStaff(account, null, null);
			List<StaffBean> l = departmentStaffs.stream().map(t -> factory.getMapper(StaffMapper.class).queryForObject(t.getStaffId())).collect(Collectors.toList());
			staffs.addAll(l);
		}
		if(Objects.equal("2", type)) { //部门
			List<StaffBean> l = factory.getMapper(StaffMapper.class).queryByDepartmentCode(account);
			staffs.addAll(l);
		}
		return staffs;
	}

    @Override
    @TaskAnnotation("queryForList")
    public PageBean<RoleLineBean> queryForList(SessionFactory factory, String name, Integer page, Integer pageSize) {
        RoleLineMapper mapper = factory.getMapper(RoleLineMapper.class);
        List<RoleLineBean> list = mapper.queryForList(name,page,pageSize);
        int total = mapper.countForList(name);
        PageBean<RoleLineBean> result = new PageBean<>(list,total);
        return result;
    }

    @Override
    @TaskAnnotation("save")
    public MessageBean<String> save(SessionFactory factory, RoleLineBean role, StaffBean user) {
        MessageBean<String> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(),"保存成功",String.class);
        RoleLineMapper mapper = factory.getMapper(RoleLineMapper.class);
        RoleLineBean bean = mapper.queryByCode(role.getCode());
        if (StringUtils.isEmpty(role.getId())) {
            DisposeBeanUtil.disposeInsert(user,role);
            if (bean != null) {
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("编码已存在");
                return msg;
            }
            mapper.insert(role);
        } else {
            DisposeBeanUtil.disposeUpdate(user,role);
            if (bean != null && !bean.getId().equals(role.getId())) {
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("编码已存在");
                return msg;
            }
            mapper.update(role);
        }
        return msg;
    }

    @Override
    @TaskAnnotation("delete")
    public void delete(SessionFactory factory, String id) {
        RoleLineMapper mapper = factory.getMapper(RoleLineMapper.class);
        mapper.delete(id);
    }

    @Override
    @TaskAnnotation("queryForObject")
    public RoleLineBean queryForObject(SessionFactory factory, String id) {
        RoleLineMapper mapper = factory.getMapper(RoleLineMapper.class);
        return mapper.queryForObject(id);
    }

    @Override
    @TaskAnnotation("insertRoleLineTeam")
    public void insertRoleLineTeam(SessionFactory factory, RoleLineTeamBean bean) {
        RoleLineMapper mapper = factory.getMapper(RoleLineMapper.class);
        bean.setId(WorkflowUtil.getObjectId());
        mapper.insertRoleLineTeam(bean);
    }

    @Override
    @TaskAnnotation("deleteRoleLineTeam")
    public void deleteRoleLineTeam(SessionFactory factory, String roleLineTeamId) {
        RoleLineMapper mapper = factory.getMapper(RoleLineMapper.class);
        mapper.deleteRoleLineTeamUserByTeamId(roleLineTeamId);
        mapper.deleteRoleLineTeam(roleLineTeamId);
    }

    @Override
    @TaskAnnotation("deleteRoleLineTeamUser")
    public void deleteRoleLineTeamUser(SessionFactory factory, String id) {
        RoleLineMapper mapper = factory.getMapper(RoleLineMapper.class);
        mapper.deleteRoleLineTeamUser(id);
    }

    @Override
    @TaskAnnotation("batchInsertRoleLineTeamUser")
    public void batchInsertRoleLineTeamUser(SessionFactory factory, List<RoleLineTeamUserBean> list,String teamId) {
        RoleLineMapper mapper = factory.getMapper(RoleLineMapper.class);
        mapper.deleteRoleLineTeamUserByTeamId(teamId);
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(item -> {
                item.setId(WorkflowUtil.getObjectId());
            });
        }
        if (!CollectionUtils.isEmpty(list)) {
            mapper.batchInsertRoleLineTeamUser(list);
        }
    }

    @Override
    @TaskAnnotation("review")
    public List<RoleLineTeamBean> review(SessionFactory factory, String roleId) {
        RoleLineMapper mapper = factory.getMapper(RoleLineMapper.class);
        List<RoleLineTeamBean> list = mapper.queryRoleLineTeamByRoleId(roleId);
        list.forEach(item -> {
            item.setChildren(mapper.queryRoleLineTeamUserByTeamId(item.getId()));
        });
        return list;
    }

    @Override
    @TaskAnnotation("queryTeamByRoleId")
    public List<RoleLineTeamBean> queryTeamByRoleId(SessionFactory factory, String roleId) {
        RoleLineMapper mapper = factory.getMapper(RoleLineMapper.class);
        return mapper.queryRoleLineTeamByRoleId(roleId);
    }

    @Override
    @TaskAnnotation("queryTeamUserByTeamId")
    public List<RoleLineTeamUserBean> queryTeamUserByTeamId(SessionFactory factory, String teamId) {
        RoleLineMapper mapper = factory.getMapper(RoleLineMapper.class);
        return mapper.queryRoleLineTeamUserByTeamId(teamId);
    }
}
